﻿using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SelfMadeMillionaire.Core.Services;
using SelfMadeMillioniare.API.Helpers;
using SelfMadeMillioniare.API.TransportObjects;
using SelfMadeMillioniare.API.TransportObjects.Enums;
using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Enums;
using System.Web.Configuration;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.BLL.Services;
using SelfMadeMillionaire.DAL.Repositories;
using SelfMadeMillionaire.DAL;

namespace SelfMadeMillioniare.API.Controllers
{
    public class UserController : BaseApiController
    {
        private const string PhoneField = "phone";
        private const string CountryField = "country";
        private const string CityField = "city";
        private const string ZipField = "zip";
        private const string FirstNameField = "firstname";
        private const string LastNameField = "lastname";
        private const string BirthDayField = "birthday";
        private const string FaceBookIdField = "facebook_id";
        private const string UserIdField = "user_id";
        private const string ItemStartField = "item_start";
        private const string ItemOffsetField = "item_offset";
        private const string AvatarField = "avatar_data";
        private const string RadiusField = "push_radius";
        private const string SexField = "sex";
        private const string NotificationIntervalField = "notifications_interval";
        private const string LatitudeField = "lat";
        private const string LongitudeField = "lon";
        private const string DeviceTokenField = "device_token";
        private const string DeviceTypeField = "device_type";


        /// <summary>
        /// Авторизация пользователя
        /// </summary>
        /// <returns>Значение типа string (token)</returns>
        [HttpPost]
        public HttpResponseMessage Login()
        {
            string device_token = CurrentRequest.Form[DeviceTokenField] ?? "";
            string device_type = "";//CurrentRequest.Form[DeviceTypeField];
            string userName = CurrentRequest.Form[UserNameField];
            string password = CurrentRequest.Form[PasswordField];

            if (string.IsNullOrEmpty(userName))
            {
                Response.AddValidateError(UserNameField, FormatHelper.Required(UserNameField));
            }

            if (string.IsNullOrEmpty(password))
            {
                Response.AddValidateError(PasswordField, FormatHelper.Required(PasswordField));
            }

            if (Response.GetValidateErrors().Any())
            {
                return Response.CreateErrorResponse(ErrorResponceType.BadRequestParameters, Request);
            }

            using (var ctx = new DataContext())
            {
                var _subscriberService = new SubscriberService(new SubscriberRepository(ctx));
                var _userSessionService = new UserSessionService(new UserSessionRepository(ctx));
                Subscriber subscriber = _subscriberService.Get(userName);
                
                if (subscriber == null)
                {
                    /*var adminLogin = WebConfigurationManager.AppSettings["AdminLogin"];
                    var adminPassword = WebConfigurationManager.AppSettings["AdminPassword"];

                    if (userName.ToLower() == adminLogin.ToLower() && password == adminPassword)
                    {
                    
                    }
                    else
                    {
                        Response.AddLogicError(Response.Message, "Incorrect Username or Password");
                        return Response.CreateErrorResponse(ErrorResponceType.LogicError, Request);
                    }*/

                    Response.AddLogicError(Response.Message, "Incorrect Username or Password");
                    return Response.CreateErrorResponse(ErrorResponceType.LogicError, Request);
                }
                else
                {
                    if ((subscriber.Status != (byte)StatusType.Active) || (subscriber.PasswordHash != PasswordUtility.GetPasswordHash(password)))
                    {
                        Response.AddLogicError(Response.Message, "Incorrect Username or Password");
                        return Response.CreateErrorResponse(ErrorResponceType.LogicError, Request);
                    }

                    subscriber.TokenApi = Guid.NewGuid().ToString().ToLower();
                    _subscriberService.Update(subscriber);

                    ClearDeviceTokens(_subscriberService, subscriber, device_token, device_type);
                    
                    UserSession session = new UserSession();
                    session.Subscriber = subscriber;
                    session.DeviceToken = device_token;
                    session.DeviceType = device_type;
                    session.LastActivityDateTime = DateTime.Now;
                    session.SessionToken = subscriber.TokenApi;
                    _userSessionService.Insert(session);

                    return Response.CreateSuccessResponce(subscriber.TokenApi, Request);

                }
            }
           
        }

        private void ClearDeviceTokens(SubscriberService service, Subscriber currentUser, string deviceToken, string deviceType)
        {
            foreach (var userByDevice in service.GetByDeviceKey(deviceToken))
            {
                if (userByDevice.ID != currentUser.ID)
                {
                    userByDevice.DeviceKey = "";
                    userByDevice.DeviceType = "";
                    userByDevice.LastPingDateTime = DateTime.UtcNow;
                    service.Update(userByDevice);
                }
            }

            currentUser.DeviceKey = deviceToken;
            currentUser.DeviceType = deviceType;
            currentUser.LastPingDateTime = DateTime.UtcNow;
            service.Update(currentUser);
        }
    }
}
